import Header from '../common/header'
import {
  List,
  SwipeAction,
  Radio,
  Ellipsis,
  Stepper,
  Button,
  Empty,
  Toast
} from 'antd-mobile'
import '../assets/css/cart.css'
import { useState } from 'react'
import { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { getCartList, delCart } from '../request/app'

function Cart () {
  let [arr, setArr] = useState([])
  let [sumPrice, setSumPrice] = useState(0)
  let Navigate = useNavigate()
  const [value, setValue] = useState(false)

  //点击删除
  function dellist (id) {
    delCart({ id: id }).then(res => {
      if (res.code == 200) {
        alert('删除成功')
      }
    })
    getCartList({
      uid: JSON.parse(sessionStorage.getItem('userInfo')).uid
    }).then(res => {
      if (res.code == 200) {
        let shoplist =
          res.list[1].content == null ? [] : [...res.list[1].content]
        //获取数据
        setArr([...shoplist])
      }
    })
  }

  //点击实现全选控制单选
  function checkAll (v) {
    setValue(v)
    let newArr = []
    arr.map(item => {
      let shop = {
        ...item,
        checked: v
      }
      newArr.push(shop)
    })
    setArr([...newArr])
  }

  //点击实现单选控制全选
  function checkOne (v, i) {
    let shop = {
      ...arr[i],
      checked: v
    }
    let newArr = arr
    newArr[i] = shop
    setArr([...newArr])
    setValue(arr.every(item => item.checked))
  }

  //计算总价格
  function AllPrice () {
    let sum = 0
    arr.map(item => {
      if (item.checked) {
        sum += item.num * item.price
      } else {
        sum += 0
      }
      setSumPrice(sum.toFixed(2))
    })
  }

  //点击跳转到订单页
  function goDorder () {
    if (arr.some(item => item.checked) == false) {
      alert('请勾选至少一项')
      return
    }
    let shopInfo = []
    arr.map(item => {
      if (item.checked) {
        shopInfo.push(item)
      }
    })
    sessionStorage.setItem('shopInfo', JSON.stringify(shopInfo))
    Navigate('/order')
  }

  // 页面一加载就调用接口
  useEffect(() => {
    if (!JSON.parse(sessionStorage.getItem('userInfo'))) {
      alert('去登录')
      Navigate('/login')
      return
    }
    getCartList({
      uid: JSON.parse(sessionStorage.getItem('userInfo')).uid
    }).then(res => {
      if (res.code == 200) {
        console.log(res)
        let shoplist =
          res.list[1].content == null ? [] : [...res.list[1].content]
        //获取数据
        setArr([...shoplist])
      }
    })
  }, [])
  useEffect(() => {
    AllPrice()
  })

  return (
    <div className='cartBox'>
      {/* 头部 */}
      <Header title={'购物车'} />
      <div className='titleBox'>
        <p>全部(20)</p>
        <p>降价(4)</p>
        <p>常买(2)</p>
        <p>分类</p>
      </div>
      {/* 购物车主体 */}
      <div className='bigBox'>
        {arr.length == 0 ? (
          <Empty
            style={{ padding: '64px 0' }}
            imageStyle={{ width: 128 }}
            description='暂无数据'
          />
        ) : (
          ''
        )}

        {arr.map((item, idx) => {
          return (
            <div className='listBox' key={item.id}>
              <List>
                <SwipeAction
                  closeOnAction={false}
                  closeOnTouchOutside={false}
                  rightActions={[
                    {
                      key: 'delete',
                      text: '删除',
                      color: 'danger'
                    }
                  ]}
                  onAction={() => dellist(item.id)}
                >
                  <div className='shopBox'>
                    <Radio
                      onChange={val => checkOne(val, idx)}
                      checked={item.checked}
                    />
                    <img src={item.img} />
                    <div className='textBox'>
                      <Ellipsis direction='end' content={item.goodsname} />
                      <Ellipsis
                        direction='end'
                        content={item.goodsname}
                        className='sText'
                      />
                      <h3>比加入时降价￥100</h3>
                      <p>
                        ￥<span>{item.price}</span>
                        <s>￥999</s>
                      </p>
                      <Stepper
                        min={1}
                        max={99}
                        className='bjq'
                        defaultValue={item.num}
                      />
                    </div>
                  </div>
                </SwipeAction>
              </List>
            </div>
          )
        })}
      </div>
      {/* 底部结算 */}
      <div className='botBox'>
        <Radio onChange={val => checkAll(val)} checked={value}>
          全选
        </Radio>
        <p>
          <span className='sp1'>合计</span>
          <br />
          <span className='sp2'>已免运费</span>
        </p>
        <p>
          <span className='sp3'>￥{sumPrice}</span>
          <br />
          <span className='sp2'>已优惠￥222元</span>
        </p>
        <Button className='btn' shape='rounded' onClick={() => goDorder()}>
          去结算
        </Button>
      </div>
    </div>
  )
}
export default Cart
